<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden; min-height: 150px"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onBlur="editOnBlur"
      @onChange="editOnBlur"
    />
  </div>
</template>
<script setup>
import axios from 'axios'
// import config from "@/utils/config";
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { TokenKey } from '#/constant'
import {
  getCookies
} from '@/utils/storage'

const props = defineProps({
  value: String
})
const emits = defineEmits()

const mode = 'default'
const editorRef = shallowRef()
const valueHtml = ref('')

const toolbarConfig = {
  excludeKeys: ['group-video', 'fullScreen', 'insertImage', 'insertLink']
}

const handleCreated = (editor) => {
  editorRef.value = editor
}
const Authorization = getCookies(TokenKey) || ''

const token = window.localStorage.getItem('token')
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload (file, insertFn) {
        const formData = new FormData()
        formData.append('file', file, file.name)
        axios({
          url: process.env.VUE_APP_URL + '/uploader/single?categoryCode=all',
          data: formData,
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: 'Bearer ' + Authorization
          }
        })
          .then(({ data: res }) => {
            console.log(res)
            insertFn(res.data, '', '')
          })
          .catch(() => {
            window.$message.error('图片上传出错')
          })
      }
    }
  }
}

const editOnBlur = (editor) => {
  emits('change', valueHtml.value)
}

defineExpose({
  getHTML () {
    return editorRef.value.getHtml()
  }
})

watch(
  () => props.value,
  (data) => {
    valueHtml.value = data
  },
  { deep: true, immediate: true }
)

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>
